package com.googlecode.garbagecan.clickstudy.page.form;

import com.googlecode.garbagecan.clickstudy.BorderTemplate;
import com.googlecode.garbagecan.clickstudy.page.HomePage;
import com.googlecode.garbagecan.clickstudy.entity.customer.Customer;
import com.googlecode.garbagecan.clickstudy.service.customer.CustomerService;
import org.apache.click.control.*;
import org.apache.click.extras.control.DateField;
import org.apache.click.extras.control.EmailField;
import org.apache.click.util.Bindable;

public class AdvancedFormPage extends BorderTemplate {
	@Bindable
	protected String title = "Advanced Form";

	@Bindable
	protected Form form = new Form();

	@Bindable
	protected String msg;

	private Select investmentSelect = new Select("investments");
	
	public AdvancedFormPage() {
		FieldSet fieldSet = new FieldSet("Customer");
		form.add(fieldSet);

		TextField nameField = new TextField("name", true);
		nameField.setMinLength(5);
		nameField.setFocus(true);
		fieldSet.add(nameField);

		fieldSet.add(new EmailField("email", true));

		fieldSet.add(investmentSelect);

		fieldSet.add(new DateField("dateJoined", true));
		fieldSet.add(new Checkbox("active"));

		form.add(new Submit("ok", " OK ", this, "onOkClicked"));
		form.add(new Submit("cancel", this, "onCancelClicked"));
	}

	@Override
	public void onInit() {
		CustomerService customerService = CustomerService.getInstance();
		investmentSelect.add(Option.EMPTY_OPTION);
		investmentSelect.addAll(customerService.getInvestmentCatetories());
	}

	public boolean onOkClicked() {
		if (form.isValid()) {
			Customer customer = new Customer();
			form.copyTo(customer);
			CustomerService.getInstance().add(customer);
			form.clearValues();
			msg = "A new customer record has been created.";
		}
		return true;
	}

	public boolean onCancelClicked() {
		setRedirect(HomePage.class);
		return false;
	}
}
